<?php

namespace app\common\model;

use think\Db;
use think\Model;


class Commission extends Model
{

    

    

    // 表名
    protected $name = 'commission';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text',
	    'status_text'
    ];
    
	const STATUS_WAIT = 0;
	const STATUS_Y = 1;
	const STATUS_CANCEL = 2;
	
	public static $statusList = [
		self::STATUS_Y => '已发放',
		self::STATUS_WAIT => '待发放',
		self::STATUS_CANCEL => '已取消'
	];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function user() {
		return $this->belongsTo('user', 'user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	public function relationuser() {
		return $this->belongsTo('user', 'relation_user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 添加返利记录
	 * @param $userId 用户ID
	 * @param $relationUserId 关联用户ID
	 * @param $orderId 订单ID
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @return false|int
	 */
	public function addRow($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount) {
		$res = $this->isUpdate(false)
			->save([
				'id' => '',
				'user_id' => $userId,
				'relation_user_id' => $relationUserId,
				'order_id' => $orderId,
				'goods_id' => $goodsId,
				'order_goods_id' => $orderGoodsId,
				'amount' => $amount,
			]);
		return $res;
	}
	
	/**
	 * 添加返利记录
	 * @param $userId
	 * @param $relationUserId
	 * @param $orderId
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @param string $remark
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function rebate($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount, $remark = '') {
		$user = \app\admin\model\User::get($userId);
		//添加用户余额
		$userRes = Db::name('user')
			->where(['id' => $userId])
			->setInc('money', $amount);
		if(!$userRes) {
			$this->error = '添加用户余额出错';
			return false;
		}
		
		
		//记录佣金记录
		$rowRes = $this->addRow($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount);
		if(!$rowRes) {
			$this->error = '添加佣金记录出错';
			return false;
		}
		
		
		//添加流水记录
		$fundsModel = new Funds();
		$fundsRes = $fundsModel->addRecord($userId, $amount, $user['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsModel::TYPE_REBATE, $orderId,$remark, $relationUserId);
		if(!$fundsRes) {
			$this->error = '添加资金记录出错';
			return false;
		}
		
		return true;
	}
	
	
	/**
	 * 代理商返利
	 * @param $parents
	 * @param $rule
	 * @param $relationUserId
	 * @param $orderId
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $number
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function agentRebate($parents, $rule, $relationUserId, $orderId, $goodsId, $orderGoodsId, $number) {
		if($parents && ($rule['agent_owner'] > 0 || $rule['agent_shop'] > 0 || $rule['agent_agent'] > 0 || $rule['agent_partner'] > 0 || $rule['agent_founder'] > 0)) {
			$agents = [];
			$level = \app\admin\model\User::LEVEL_VIP;
			
			//获取推荐人中从小到大等级的代理
			foreach ($parents as $item) {
				if($item['level'] > $level) {
					$level = $item['level'];
					$agents[$level] = $item['user_id'];
					
					if($level == \app\admin\model\User::LEVEL_FOUNDER) {
						break;
					}
				}
			}
			
			
			if($agents) {
				//不同等级对应的返利金额
				$rebateAmount = [
					2 => $rule['agent_owner'],
					3 => $rule['agent_shop'],
					4 => $rule['agent_agent'],
					5 => $rule['agent_partner'],
					6 => $rule['agent_founder'],
				];
				
				
				$levelList = \app\admin\model\User::$levelList;
				//领取代理等级以下没有被领走的奖励
				foreach ($agents as $level => $userId) {
					$amount = 0;
					foreach ($rebateAmount as $key => $value) {
						if($key <= $level) {
							$amount += $value;
							unset($rebateAmount[$key]);
						}
					}
					
					if($amount > 0) {
						$agentRes = $this->rebate($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount*$number, $levelList[$level]);
						if(!$agentRes) {
							$this->error = $levelList[$level].'返利出错';
							return false;
						}
					}
					
				}
			}
		}
		
		return true;
	}
}
